<template>
  <a-layout>

    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <a-row :gutter="24">
        <a-col :span="8">
          <p>
            <a-form
                layout="inline"
                :model="formState"
                @finish="handleQuery({page:1,size:pagination.pageSize})"
            >
              <!--
                            <a-form-item>
                              <a-input v-model:value="formState.name" placeholder="书籍名称">
                                <template #prefix>
                                  <UserOutlined style="color: rgba(0, 0, 0, 0.25)"/>
                                </template>
                              </a-input>
                            </a-form-item>

                            <a-form-item>
                              <a-button type="primary" @click="handleQuery({page:1,size:pagination.pageSize})">查询</a-button>
                            </a-form-item>
              -->


              <a-forom-item>
                <a-button type="primary" @click="add()">新增</a-button>
              </a-forom-item>

            </a-form>

          </p>
          <a-table
              v-if="level1.length>0"
              :columns="columns"
              :row-key="record=>record.id"
              :data-source="level1"
              :pagination="pagination"
              :loading="loading"
              @change="handleTableChange"
              size="small"
              :defaultExpandAllRows="true"
          >
            <!--文档封面-->
            <template #neme="{text:record}">
              {{ record.sort }} {{ text }}
            </template>

            <!--按钮-->
            <template v-slot:action="{text,record}">
              <a-space size="small">
                <a-button type="primary" @click="edit(record)" size="small">编辑</a-button>
                <a-popconfirm
                    title="确认删除？"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="del(record.id)"
                    @cancel="cancel"
                >
                  <a-button type="danger" size="small">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-col>
        <a-col :span="16">
          <p>
            <a-form layout="inline" :model="param">
              <a-form-item>
                <a-button type="primary" @click="handleSave">保存</a-button>
              </a-form-item>
            </a-form>
          </p>

          <a-form :model="doc" layout="vertical">
            <a-form-item>
              <a-input v-model:value="doc.name" placeholder="名称"/>
            </a-form-item>
            <a-form-item>
              <a-tree-select
                  v-model:value="doc.parent"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeSelectData"
                  placeholder="选择父文档"
                  tree-default-expand-all
                  :replaceFields="{title:'name',key:'id',value:'id'}"
              >
              </a-tree-select>

            </a-form-item>
            <!--
                  <a-form-item label="父文档">
                    <a-select
                        ref="select"
                        v-model:value="doc.parent"
                    >
                      <a-select-option value="0">无</a-select-option>
                      <a-select-option v-for="c in level1" :key="c.id" :value="c.id" :disabled="doc.id===c.id">
                        {{ c.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>-->
            <a-form-item>
              <a-input v-model:value="doc.sort" placeholder="顺序"/>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handlePreviewContent()">
                <EyeOutlined></EyeOutlined>
                内容预览
              </a-button>
            </a-form-item>
            <a-form-item>
              <div id="content"></div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-drawer width="900" placement="right" :closable="false" :visible="drawerVisible" @close="onDrawerClose">
        <div class="wangeditor" :innerHTML="previewHtml"></div>
      </a-drawer>

    </a-layout-content>
  </a-layout>

  <!--编辑对话框-->
  <!--
    <a-modal
        title="Title"
        v-model:visible="modalVisible"
        :confirm-loading="ModalLoading"
        @ok="handleModalOk"
    >
    </a-modal>
  -->

</template>

<script lang="ts">
import {defineComponent, onMounted, ref} from 'vue';
import axios from "axios";
import {message} from "ant-design-vue";
import {UserOutlined, LockOutlined, EyeOutlined} from '@ant-design/icons-vue';
import {Tool} from "@/util/tool.ts";
import {useRoute} from "vue-router";
import E from 'wangeditor';

export default defineComponent({
  name: 'AdminDoc',
  components: {
    EyeOutlined,
    UserOutlined,
    LockOutlined,
  },

  setup() {

    const route = useRoute()
    const level1 = ref();
    level1.value = [];
    const docs = ref();
    const formState = ref({
      name: ''
    })
    const pagination = ref({
      hideOnSinglePage: true,
      current: 1,
      pageSize: 100,
      total: 0
    });
    const treeSelectData = ref();
    treeSelectData.value = [];
    const loading = ref(false);
    const columns = [

      {
        title: '名称',
        dataIndex: 'name',
        slot: {customRender: 'name'}
      },
      {
        title: 'Action',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];

    /*数据查询*/
    const handleQuery = () => {
      loading.value = true;
      level1.value = [];
      axios.get("/doc/all/" + route.query.ebookId).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          docs.value = data.content;
          console.log("原始数据:", docs.value);
          level1.value = [];
          level1.value = Tool.array2Tree(docs.value, 0);
          console.log("树形结构:", level1);
          treeSelectData.value = Tool.copy(level1.value);
          treeSelectData.value.unshift({id: 0, name: '无'});
        } else {
          message.error(data.message);
        }

      })
    };
    /*内容查询*/
    const handleQueryContent = () => {
      axios.get("/doc/find-content/" + doc.value.id, {}).then((response) => {
        const data = response.data;
        if (data.success) {
          editor.txt.html(data.content);
        } else {
          message.error(data.message);
        }

      })
    };
    /*表格点击页码时触发*/
    const handleTableChange = (pagination: any) => {
      console.log("自带分页参数:" + pagination.current);
      if (formState.value.name == '') {
        handleQuery()
      } else {
        handleQuery()
      }
    };
    /*表单*/

    const doc = ref();
    doc.value = {ebookId: route.query.ebookId,};
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    let editor: any;
    const createEditor = () => {
      editor = new E('#content');
      editor.config.zIndex = 0;
      editor.create();

    }
    const handleSave = () => {
      modalLoading.value = true;
      doc.value.content = editor.txt.html();
      axios.post("/doc/save", doc.value).then((response) => {
        modalLoading.value = false;
        const data = response.data;//data=commonResp

        if (data.success) {
          modalVisible.value = false;
          //重新加载列表
          handleQuery();
          message.success("操作成功");
        } else {
          message.error(data.message)
        }
      });
    };

    /* 将某节点及其子孙节点全部设置为disabled*/
    const setDisable = (treeSelectData: any, id: any) => {
      console.log(treeSelectData, id);

      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id == id) {
          //如果当前节点是目标节点
          console.log("disabled", node);
          //将目标节点设置为disabled
          node.disabled = true;

          //遍历所有子节点，将所有子节点全部加上disabled
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              setDisable(children, children[j].id)
            }
          }
        } else {
          //如果当前节点不是目标节点，则到其他节点再找
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            setDisable(children, id);
          }
        }
      }
    };
    /*查找整根树枝*/
    const ids: Array<string> = [];
    const getDeleteIds = (treeSelectData: any, id: any) => {
      console.log(treeSelectData, id);

      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id == id) {
          //如果当前节点是目标节点
          console.log("disabled", node);
          //将目标ID放入结果集ids
          // node.disabled = true;
          ids.push(id);

          //遍历所有子节点
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              getDeleteIds(children, children[j].id)
            }
          }
        } else {
          //如果当前节点不是目标节点，则到其他节点再找
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            getDeleteIds(children, id);
          }
        }
      }
    };
    // ----------------富文本预览--------------
    const drawerVisible = ref(false);
    const previewHtml = ref();
    const handlePreviewContent = () => {
      const html = editor.txt.html();
      previewHtml.value = html;
      drawerVisible.value = true;
    };
    const onDrawerClose = () => {
      drawerVisible.value = false;
    };
    onMounted(() => {

      handleQuery();
      setTimeout(function () {
        if (editor == null) {
          createEditor();
        } else {
          editor.destroy();//这里做了一次判断，判断编辑器是否被创建，如果创建了就先销毁。
          createEditor();
        }

      })
    });


    const edit = (record: any) => {
      modalVisible.value = true;
      doc.value = Tool.copy(record);

      //不能选择当前节点及其所有子孙节点作为父节点，会使树断开
      treeSelectData.value = Tool.copy(level1.value);
      setDisable(treeSelectData.value, record.id);

      //为树选择添加一个“无”
      treeSelectData.value.unshift({id: 0, name: '无'});
      setTimeout(function () {
        if (editor == null) {
          createEditor();
        } else {
          editor.destroy();//这里做了一次判断，判断编辑器是否被创建，如果创建了就先销毁。
          createEditor();
        }
      })
      handleQueryContent();
    }

    const add = () => {
      editor.txt.html("")
      modalVisible.value = true;
      doc.value = {
        ebookId: route.query.ebookId,
      };

      treeSelectData.value = Tool.copy(level1.value);
      treeSelectData.value.unshift({id: 0, name: '无'});
      setTimeout(function () {
        if (editor == null) {
          createEditor();
        } else {
          editor.destroy();//这里做了一次判断，判断编辑器是否被创建，如果创建了就先销毁。
          createEditor();
        }
      })
    }

    const del = (id: number) => {
      getDeleteIds(level1.value, id);
      axios.delete("/doc/delete/" + ids.join(", ")).then((response) => {
        const data = response.data;//data=commonResp
        if (data.success) {
          //重新加载列表
          handleQuery();
        }
      });

    }
    /*搜索*/
    const handleFinish = (p: any) => {
      handleQuery()
    }
    const handleFinishFailed = () => {
      console.log("error")
    }

    return {
      // docs,
      level1,
      doc,
      add,
      del,
      pagination,
      columns,
      loading,
      handleTableChange,
      edit,
      modalVisible,
      modalLoading,
      handleSave,
      formState,
      handleFinish,
      handleFinishFailed,
      handleQuery,
      treeSelectData,
      drawerVisible,
      previewHtml,
      handlePreviewContent,
      onDrawerClose,
    }
  }


});
</script>
